<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/

class tag_api {

	public function getTagsByCategory($catid){
		return load_db('tag')->getTagsByCategory($catid);
	}

	public function getTags($page,$pagesize){
		return load_db('tag')->search($page,$pagesize);
	}

	public function getTagByid($id){
		$tagdb = load_db('tag');
		$con['tag_id'] = $id;
		return $tagdb->findJoin($con);
	}

	public function deleteTagByid($id){
		$tagdb = load_db('tag');
		$tag = $this->getTagByid($id);
		$result = $tagdb->delete(array('tag_id'=>$id));
		if($result) $tagdb->updateTagsCacheByCategory($tag['category_id']);
		return $result;
	}

	public function addTag($data){
		$tagdb = load_db('tag');
		$result = $tagdb->create($data);
		if($result) $tagdb->updateTagsCacheByCategory($data['category_id']);
		return $result;
	}

	public function updateTagByid($id,$update){
		$tagdb = load_db('tag');
		$tag = $this->getTagByid($id);
		$result = $tagdb->update(array('tag_id'=>$id),$update);
		if($result) {
			$tagdb->updateTagsCacheByCategory($update['category_id']);
			if($update['category_id']!=$tag['category_id'])
				$tagdb->updateTagsCacheByCategory($tag['category_id']);
		}
		return $result;
	}

	public function getAllTagItemsByCategory($cid){
		$tagGroups = $this->getTagsByCategory($cid);
		if($tagGroups){
			$tags = array();
			foreach ($tagGroups as $tagGroup){
				$tags[] = $tagGroup['tags'];
			}
			$tags = join(',', $tags);
			$tags = explode(',', $tags);
			$clean = array();
			foreach ($tags as $tag){
				$clean[] = trim($tag);
			}
			return $clean;
		}
		return false;
	}

	public function collectFromTxt($cid,$txt,$maxnum){
		$tags = $this->getAllTagItemsByCategory($cid);
		$collected = array();
		$tg = array();
		$ts = array();
		if($tags){
			foreach ($tags as $tag){
				if(strexists($txt, $tag)){
					$tg[]=$tag;
					$ts[]=pzxencode($tag);
				}
				if(array_length($tg)>=$maxnum){
					break;
				}
			}
		}
		$collected['tag'] = $tg;
		$collected['search'] = $ts;
		return $collected;
	}
}

